<template>
    <el-dialog
            :title="title"
            :visible.sync="isVisible"
            :width="width"
            :before-close="handleClose"
            :lock-scroll="true"
            :close-on-click-modal="false"
            custom-class="pub_dialog"
            @open="getData"
    >
        <VForm
                ref="vformComponents"
                :form="formData.form"
                :options="formData.options"
                :rules="formData.rules"
                :labelWidth="formData.labelWidth"
                :rowspan="rowspan"
                @changeAddress="changeAddress"
                @changeGdArea="changeGdArea"
                @toLoadMethods="toLoadMethods"

        ></VForm>



        <span slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="sure">确 定</el-button>
    </span>
    </el-dialog>
</template>

<script>
    import { riskHazardDetail,
            riskHazardUpdate,
            riskHazardAdd } from '@/api/risk/riskHazard'
    import { treeDataChild} from '@/api/risk/treeData'
    import { alarmFacilityList} from '@/api/alarm/facility'
    import VForm from "@/components/VForm/index";
    import { buildProjectList} from '@/api/build/project'
    export default {
        components: {
            VForm,
        },
        props: {
            width: {
                type: String,
                default: "70%",
            },
            title: {
                type: String,
                default: "详情",
            },
            id:{},
            openType:{
                type:String,
                default:"add"
            },
            dialogVisible: {
                type: Boolean,
                default: false
            }
        },
        watch: {
            'width': {
                handler(newVal, oldVal) {
                    console.log('newVal===',newVal, oldVal)
                    let w = this.width.split('%')[0]
                    if(w>=60){
                        this.rowspan = 2
                    }else{
                        this.rowspan = 1
                    }
                },
                deep: true,
                immediate: true
            },
            'bClassifyOptions':{
                handler(newVal, oldVal) {
                    this.formData.options.forEach(t=>{
                        if(t.key=='bclassify'){
                        t.option.data = newVal
                    }
                })
                },
                deep: true,
                immediate: true
            },
            'sClassifyOptions':{
              handler(newVal, oldVal) {
                this.formData.options.forEach(t=>{
                  if(t.key=='sclassify'){
                    t.option.data = newVal
                  }
                })
              },
              deep: true,
              immediate: true
            },
            'categoryOptions':{
              handler(newVal, oldVal) {
                this.formData.options.forEach(t=>{
                  if(t.key=='category'){
                    t.option.data = newVal
                  }
                })
              },
              deep: true,
              immediate: true
            },
            'gradeOptions':{
              handler(newVal, oldVal) {
                this.formData.options.forEach(t=>{
                  if(t.key=='grade'){
                    t.option.data = newVal
                  }
                })
              },
              deep: true,
              immediate: true
            },
            'stateOptions':{
              handler(newVal, oldVal) {
                this.formData.options.forEach(t=>{
                  if(t.key=='state'){
                    t.option.data = newVal
                  }
                })
              },
              deep: true,
              immediate: true
            },

            'facilityOptions':{
              handler(newVal, oldVal) {
                this.formData.options.forEach(t=>{
                  if(t.key=='facilityId'){
                    t.option.data = newVal
                  }
                })
              },
              deep: true,
              immediate: true
            },
        },
        computed: {
            isVisible: {
                get() {
                    return this.dialogVisible
                },
                set() {
                    this.close()
                }
            }
        },
        data() {
            return {
                rowspan:1,
                dict:{},
                formData: {
                    form: {
                            flagCode:"1",
                            reportTime:"",
                            name:"",
                            bclassify:"",

                            sclassify:"",
                            category:"",
                            address:"",
                            memo:"",
                            grade:"",
                            state:"",
                            reportName:"",
                            reportContact:"",


                            objClassify:"",
                            objName:"",
                            lon:"",
                            lat:"",
                            provinceCode:"",
                            cityCode:"",
                            countyCode:"",
                            areaCode:"",
                            updateTime:"",
                            updateBy:"",

                            reportUnit:"",
                            img:[],
                            discoveryTime:"",

                            mapData:null,

                            fromType:"",
                            facilityId:'',
                            facilityName:'',
                            buildingId:'',
                        },
                    options: [

                       {
                           title: "隐患上报时间",
                           key: "reportTime",
                           type: "date",
                       },
                       {
                           title: "隐患名称",
                           key: "name",
                           type: "text",
                       },
                        {
                          title: "所属工地",
                          key: "buildingId",
                          type: "select",
                          multiple:false,
                          option: {
                            data: [],
                            props: {
                              key: "id", // 指定key对应data的字段
                              label: "projectName", // 指定label对应data的字段
                              value: "id", // 指定value对应data的字段
                            },
                          },
                        },
                       {
                            title: "隐患大类",
                            key: "bclassify",
                            type: "select",
                            multiple:false,
                            event:'changeBclassify',
                            option: {
                                data: this.bClassifyOptions,
                                props: {
                                    key: "id", // 指定key对应data的字段
                                    label: "label", // 指定label对应data的字段
                                    value: "name", // 指定value对应data的字段
                                },
                            },
                        },
                       {
                        title: "隐患细类",
                        key: "sclassify",
                        type: "select",
                        multiple:false,
                        event:'changeSclassify',
                        option: {
                          data: this.sClassifyOptions,
                          props: {
                            key: "id", // 指定key对应data的字段
                            label: "label", // 指定label对应data的字段
                            value: "name", // 指定value对应data的字段
                          },
                        },
                       },
                       {
                        title: "三级类别",
                        key: "category",
                        type: "select",
                        multiple:false,
                        option: {
                          data: this.categoryOptions,
                          props: {
                            key: "id", // 指定key对应data的字段
                            label: "label", // 指定label对应data的字段
                            value: "name", // 指定value对应data的字段
                          },
                        },
                       },

                      {
                        title: "工地设施名称",
                        key: "facilityId",
                        type: "select",
                        multiple:false,
                        event:'changeFacilityName',
                        option: {
                          data: this.facilityOptions,
                          props: {
                            key: "id", // 指定key对应data的字段
                            label: "label", // 指定label对应data的字段
                            value: "name", // 指定value对应data的字段
                          },
                        },
                      },

                       {
                        title: "隐患等级",
                        key: "grade",
                        type: "select",
                        multiple:false,
                        option: {
                          data: this.gradeOptions,
                          props: {
                            key: "id", // 指定key对应data的字段
                            label: "label", // 指定label对应data的字段
                            value: "value", // 指定value对应data的字段
                          },
                        },
                       },
                      {
                        title: "上报单位",
                        key: "reportUnit",
                        type: "text",
                      },
                      {
                        title: "上报人",
                        key: "reportName",
                        type: "text",
                      },
                      {
                        title: "上报人电话",
                        key: "reportContact",
                        type: "text",
                      },
                      {
                        title: "发现时间",
                        key: "discoveryTime",
                        type: "date",
                      },
                     {
                         title: "隐患地址",
                        type:'mapPosition',
                        key:'mapData',
                     },
                      {
                        title: "现场照片",
                        key: "img",
                        type: "file",
                        fileType: "image",
                        listType: "picture-card",
                        uploadTextTip: "",
                        columnWidth: 'w100max'
                      },
                       {
                           title: "隐患描述",
                           key: "memo",
                           type: "textarea",
                           columnWidth: 'w100max'
                       }
                    ],
                    rules: {
                        flagCode :[
                          {max:20, message: '长度最大为20个字符', trigger: 'blur'}
                        ],
                        reportTime :[
                          { required: true, message: '请输入', trigger: 'blur' }
                        ],
                        name :[
                          { required: true, message: '请输入', trigger: 'blur' },
                          {max:64, message: '长度最大为64个字符', trigger: 'blur'}
                        ],
                        bclassify :[
                          { required: true, message: '请选择', trigger: 'blur' }
                        ],
                        sclassify :[
                          { required: true, message: '请选择', trigger: 'blur' }
                        ],
                        category :[
                          { required: true, message: '请选择', trigger: 'blur' }
                        ],
                        discoveryTime :[
                          { required: true, message: '请输入', trigger: 'blur' }
                        ],
                        address :[
                          {max:200, message: '长度最大为200个字符', trigger: 'blur'}
                        ],
                        memo :[
                          { required: true, message: '请输入', trigger: 'blur' },
                          {max:1024, message: '长度最大为1024个字符', trigger: 'blur'}
                        ],
                        grade :[
                          { required: true, message: '请选择', trigger: 'blur' }
                        ],
                        state :[
                          { required: true, message: '请选择', trigger: 'blur' }
                        ],
                        reportName :[
                          {max:50, message: '长度最大为50个字符', trigger: 'blur'}
                        ],
                        reportContact :[
                          {max:20, message: '长度最大为20个字符', trigger: 'blur'}
                        ],



                        lon :[
                          {max:36, message: '长度最大为36个字符', trigger: 'blur'}
                        ],
                        lat :[
                          {max:36, message: '长度最大为36个字符', trigger: 'blur'}
                        ],
                        provinceCode :[
                          {max:12, message: '长度最大为12个字符', trigger: 'blur'}
                        ],
                        cityCode :[
                          {max:12, message: '长度最大为12个字符', trigger: 'blur'}
                        ],
                        countyCode :[
                          {max:12, message: '长度最大为12个字符', trigger: 'blur'}
                        ],
                        areaCode :[
                          {max:12, message: '长度最大为12个字符', trigger: 'blur'}
                        ],

                    },
                    labelWidth: "140px",
                },
            // 字典
                bClassifyOptions:[],
                sClassifyOptions:[],
                categoryOptions:[],
                gradeOptions:[],
                stateOptions:[],
                facilityOptions:[],

            };
        },
        methods: {
            toLoadMethods(methods){
              this[methods]();
            },
            changeFacilityName(){
              var label = this.facilityOptions.find(t=>t.name==this.formData.form.facilityId).label;
              this.formData.form.facilityName=label;

            },
            changeBclassify(){
              this.formData.form.sclassify='';
              this.sClassifyOptions=[];

              this.formData.form.category='';
              this.categoryOptions=[]

              this.formData.form.facilityId='';
              this.formData.form.facilityName='';
              this.facilityOptions=[];
              this.sendBclassifyData();
            },

            async sendBclassifyData(){
              let queryData ={}
              queryData.name='hazardBClassify';
              queryData.code =this.formData.form.bclassify;
              let res =await treeDataChild(queryData);
              if(res.code==200) {
                let that = this
                res.data.forEach(function (item,index){
                  var one ={}
                  one.label= item.label;
                  one.name=item.code;
                  one.modeType=item.modeType;
                  that.sClassifyOptions.push(one);
                })

                if(this.formData.form.sclassify!=''){
                  this.sendFacilityData();
                }
              }


            },

            changeSclassify(){
              this.formData.form.category='';
              this.categoryOptions=[];
              this.sendCategoryData();

              this.formData.form.facilityId='';
              this.formData.form.facilityName='';
              this.facilityOptions=[];
              this.sendFacilityData();
            },

            async sendCategoryData(){
              let queryData ={}
              queryData.name='hazardSClassify';
              queryData.code =this.formData.form.sclassify;
              let res =await treeDataChild(queryData);
              if(res.code==200) {
                let that = this
                res.data.forEach(function (item,index){
                  var one ={}
                  one.label= item.label;
                  one.name=item.code;
                  that.categoryOptions.push(one);
                })
              }
            },

            async sendFacilityData(){
              let queryData ={}
              let modeType = this.sClassifyOptions.find(t=>t.name==this.formData.form.sclassify).modeType;
              queryData.modeType="ALARM_"+modeType;
              queryData.areaCodeFormat = this.$store.state.account.user.deptIds;
              let res =await alarmFacilityList(queryData);
              if(res.code==200) {
                let that = this
                res.data.forEach(function (item,index){
                  var one ={}
                  one.label=item.name ;
                  one.name=item.id;
                  that.facilityOptions.push(one);
                })

              }
            },

            getCountySubIndex(cityCode){
              // 中山、东莞截取10位
              let filterList = ['442000000000','441900000000']
              if(filterList.findIndex(t=>t==cityCode)>-1){
                return 10;
              }
              return 6;
            },
            positionSubmitFormat(){

              let mapData = this.formData.form.mapData
              console.log(">>>");
              console.log(mapData);
              if(mapData){
                this.formData.form.lon = mapData.gpsX
                this.formData.form.lat = mapData.gpsY
                this.formData.form.address = mapData.address
                this.formData.form.areaCode = mapData.towncode
                if(mapData.towncode){
                  this.formData.form.provinceCode = mapData.towncode.substr(0,2).padEnd(12,'0')
                  this.formData.form.cityCode = mapData.towncode.substr(0,4).padEnd(12,'0')
                  let subIndex = this.getCountySubIndex(this.formData.form.cityCode)
                  this.formData.form.countyCode = mapData.towncode.substr(0,subIndex).padEnd(12,'0')
                }
              }
            },
            positionLoadFormat(){
              let form = this.formData.form
              let mapData = {}


                mapData.address = form.address
                mapData.gpsX = parseFloat(form.lon)
                mapData.gpsY = parseFloat(form.lat)
                mapData.towncode = form.areaCode
                this.formData.form.mapData = mapData




              console.log("mpap",mapData)
            },


            submitFormat(){

              if(this.formData.form.img==''||this.formData.form.img=='null'){
                this.formData.form.img = []
              }
              this.formData.form.img = JSON.stringify(this.formData.form.img);

            },
            loadFormat(){
              this.formData.form.img = this.formData.form.img ? JSON.parse(this.formData.form.img).map(item => {
                return {
                  name: item.name,
                  url: process.env.VUE_APP_BASE_API + 'file/api/download/' + item.fileId,
                  uid: item.uuid,
                  fileId: item.fileId,
                }
              }) : []

            },
            getCheckBoxData(value,option,type){
                if(type=="submit"){
                    if(value.length==0){
                        return null
                    }
                    let temp = [];
                    value.forEach(t=>{
                        let item = option.find(x=> x.label == t)
                    if(item!=undefined){
                        temp.push(item.value)
                    }
                })
                    return temp.join(",")
                }else {
                    if(!value){
                        return []
                    }else {
                        let data = value.split(",")
                        let temp = []
                        data.forEach(t=>{
                            let item = option.find(x=> x.value == t)
                        if(item!=undefined){
                            temp.push(item.label)
                        }
                    })
                        return temp
                    }
                }
            },
            sure(){
                console.log('sure===',this.formData.form)
                this.$refs.vformComponents.$refs.form.validate().then(res=>{
                    this.submitFormat()
                  this.positionSubmitFormat()
                    if(this.openType == "add"){
                        this.add()
                    }else{
                        this.update()
                    }
                })
            },
            add(){
                this.formData.form.id = null
                this.formData.form.delFlag=0;
                //待派单
                this.formData.form.state=1;
                // 系统录入
                this.formData.form.fromType='1';
                riskHazardAdd(this.formData.form).then(res=>{
                    if(res.code==200){
                    this.$message({
                        message: this.$t('tips.createSuccess'),
                        type: 'success'
                    })
                    this.closeSuccess()
                    }else{
                    this.$message({
                        message: this.$t('tips.systemException'),
                        type: 'error'
                    })
                    }
                })
            },
            update(){
                   riskHazardUpdate(this.formData.form).then(res=>{
                        if(res.code==200){
                        this.$message({
                             message: this.$t('tips.updateSuccess'),
                            type: 'success'
                        })
                        this.closeSuccess()
                      }else{
                        this.$message({
                            message: this.$t('tips.systemException'),
                            type: 'error'
                        })
                     }
                })
            },
            cancel(){
                this.close()
            },
            handleClose(done) {
                done()
                this.close()
            },
            closeSuccess(){
                this.$refs.vformComponents.$refs.form.resetFields();
                this.$emit('success')
            },
            close(){
                this.$refs.vformComponents.$refs.form.resetFields();
                this.$refs.vformComponents.$refs.mapPosition[0].reloadMap();
                this.$emit('close')
            },
            getData(){

              // 获取字典值
              this.bClassifyOptions = []
              this.$commonJs.filterDataDict("hazardBClassify",this.bClassifyOptions )

              this.sClassifyOptions = []
              //this.$commonJs.filterDataDict("hazardSClassify",this.sClassifyOptions )


              this.categoryOptions = []
              //this.$commonJs.filterDataDict("hazardCategory",this.categoryOptions )

              this.gradeOptions = []
              this.$commonJs.filterDataDict("patrolHazardLevel",this.gradeOptions )

              this.stateOptions = []
              this.$commonJs.filterDataDict("hazardDealState",this.stateOptions )


              let queryParam={}
              buildProjectList(queryParam).then(res=>{
                if(res.code==200){
                  this.formData.options.forEach(t=>{
                    if(t.key=='buildingId'){
                      t.option.data = res.data
                    }
                  })

                }else{
                  this.$message({
                    message: this.$t('tips.systemException'),
                    type: 'error'
                  })
                }
              })

              if(this.openType!="add"){
                  riskHazardDetail(this.id).then(res=>{
                      if(res.code==200){
                          this.formData.form = res.data

                        this.sendBclassifyData();
                        this.sendCategoryData();

                        this.loadFormat();
                        this.positionLoadFormat();


                       }else{
                          this.$message({
                              message: this.$t('tips.systemException'),
                              type: 'error'
                          })
                      }
                  })
              }
            },

            changeAddress(data){
              // console.log(data)
              this.formData.form.mapData = data
              this.formData.form.areaCode = data.areaCode
            },
            changeGdArea(data){
              console.log(data)
            },
        },


    };
</script>

<style lang="scss" scoped>

</style>
